package org.acooly.secretbox.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.acooly.secretbox.R;
import org.acooly.secretbox.service.AccountTypeService;
import org.acooly.secretbox.service.domain.AccountType;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class AccountTypeServiceImpl extends SQLiteOpenHelper implements AccountTypeService {

	private static final String TAG = "AccountTypeServiceImpl";

	private static final String DATABASE_NAME = "accounttype.db";
	private static final String TABLE_NAME = "ACCOUNTTYPE";

	private static final String ID = "ID";
	private static final String NAME = "NAME";
	private static final String ICON = "ICON";
	private static final String COMMENT = "COMMENT";
	private static final String TYPE = "TYPE";
	private static final String TABLE_CREATE = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + NAME
			+ " text not null," + ICON + " int not null, " + COMMENT + " text," + TYPE + " int);";

	private Context context;

	public AccountTypeServiceImpl(Context context) {
		super(context, DATABASE_NAME, null, 1);
		this.context = context;
	}

	@Override
	public void addAll(List<AccountType> accountTypes) {
		if (accountTypes != null && accountTypes.size() > 0) {
			for (AccountType accountType : accountTypes) {
				save(accountType);
			}
		}
	}

	@Override
	public List<AccountType> getAll() {
		SQLiteDatabase db = getReadableDatabase();
		List<AccountType> accountTypes = new ArrayList<AccountType>();
		try {
			Cursor cur = db.rawQuery("select * from " + TABLE_NAME, null);
			while (cur.moveToNext()) {
				AccountType accountType = new AccountType(cur.getInt(0), cur.getString(1), cur.getInt(2), cur.getString(3), cur.getInt(4));
				accountTypes.add(accountType);
			}
			cur.close();
			return accountTypes;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new RuntimeException("List AccountType failure:" + e.getMessage());
		} finally {
			db.close();
		}
	}

	@Override
	public void save(AccountType accountType) {
		SQLiteDatabase db = null;
		try {
			ContentValues values = new ContentValues();
			values.put(NAME, accountType.getName());
			values.put(ICON, accountType.getIcon());
			values.put(COMMENT, accountType.getComment());
			values.put(TYPE, accountType.getType());
			db = this.getWritableDatabase();
			if (accountType.getId() == 0) {
				// create
				db.insert(TABLE_NAME, null, values);
			} else {
				// update
				db.update(TABLE_NAME, values, "id=?", new String[] { String.valueOf(accountType.getId()) });
			}

		} catch (Exception e) {
			Log.e("AccountService", e.getMessage());
			throw new RuntimeException("Save account type faulure:" + e.getMessage());
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	@Override
	public void delete(int id) {
		SQLiteDatabase db = null;
		try {
			db = getWritableDatabase();
			db.delete(TABLE_NAME, " id = " + id, null);
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new RuntimeException("Delete account type faulure");
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	@Override
	public AccountType get(int id) {
		SQLiteDatabase db = getReadableDatabase();
		try {
			Cursor cur = db.rawQuery("select * from " + TABLE_NAME + " where id = ?", new String[] { String.valueOf(id) });
			AccountType accountType = null;
			if (cur.moveToNext()) {
				accountType = new AccountType(cur.getInt(0), cur.getString(1), cur.getInt(2), cur.getString(3), cur.getInt(4));
				Log.i("Get AccountType", accountType.toString());
			}
			cur.close();
			return accountType;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			throw new RuntimeException("AccountType does not exists:" + e.getMessage());
		} finally {
			db.close();
		}
	}

	public int getCount(String sql) {
		SQLiteDatabase db = null;
		try {
			db = this.getReadableDatabase();
			Cursor mCount = db.rawQuery(sql, null);
			mCount.moveToFirst();
			int count = mCount.getInt(0);
			mCount.close();
			return count;
		} catch (Exception e) {
			Log.e(TAG, e.getMessage());
			return 0;
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	public int getCount() {
		SQLiteDatabase db = null;
		try {
			db = this.getReadableDatabase();
			Cursor mCount = db.rawQuery("select count(*) from " + TABLE_NAME, null);
			mCount.moveToFirst();
			int count = mCount.getInt(0);
			mCount.close();
			return count;
		} catch (Exception e) {
			Log.e("AccountService", e.getMessage());
			return 0;
		} finally {
			if (db.isOpen()) {
				db.close();
			}
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.i(DATABASE_NAME, TABLE_CREATE);
		db.execSQL(TABLE_CREATE);
		String[] initNames = context.getResources().getStringArray(R.array.init_account_type_name);
		String[] initComments = context.getResources().getStringArray(R.array.init_account_type_comment);
		String[] initIcons = context.getResources().getStringArray(R.array.init_account_type_icon);
		for (int i = 0; i < initNames.length; i++) {
			String sql = "INSERT INTO " + TABLE_NAME + "(" + NAME + "," + ICON + "," + COMMENT + "," + TYPE + ") VALUES('" + initNames[i] + "',"
					+ context.getResources().getIdentifier(initIcons[i], "drawable", context.getPackageName()) + ",'" + initComments[i] + "',"
					+ AccountType.TYPE_SYSTEM + ");";
			Log.d(TAG, sql);
			db.execSQL(sql);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}

}
